package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;
    @Override
    public List<Address> findList() {
        //根据userid查询地址
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        wrapper.orderByDesc(Address::getIsDefault);
        List<Address> addressList = addressMapper.selectList(wrapper);
        return addressList;
    }

    @Override
    public void saveAdress(Address address) {
        //设置userid
        address.setUserId(UserHolder.get().getId());
        //保存
        addressMapper.insert(address);
    }

    @Override
    public void defaultAddress(Long id) {
        //通过userid将所有地址的default全部改为0
        Address address = new Address();
        address.setIsDefault(0);
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        addressMapper.update(address,wrapper);
        //设置相应id的default为1
        Address address1 = new Address();
        address1.setId(id);
        address1.setIsDefault(1);
        addressMapper.updateById(address1);
    }

    @Override
    public Address findDefault() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        wrapper.eq(Address::getIsDefault,1);
        Address address = addressMapper.selectOne(wrapper);
        return address;
    }

    @Override
    public Address findById(Long id) {
        Address address = addressMapper.selectById(id);
        return address;
    }

    @Override
    public void updateAddress(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void deleteAddress(Long id) {
        addressMapper.deleteById(id);
    }
}
